package com.java.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.java.entity.ExChapter;
import com.java.entity.ExChapterRecord;
import com.java.entity.ExTopic;
import com.java.entity.ExTopicOption;
import com.java.entity.ExTopicResp;
import com.java.entity.vo.ChapterRecordVo;
import com.java.entity.vo.ChapterVo;
import com.java.entity.vo.ExTopicVo;
import com.java.entity.vo.SubmitRecord;
import com.java.entity.vo.SubmitRecordItem;
import com.java.mapper.ExAccountMapper;
import com.java.mapper.ExChapterItemMapper;
import com.java.mapper.ExChapterMapper;
import com.java.mapper.ExChapterRecordMapper;
import com.java.mapper.ExTopicMapper;
import com.java.mapper.ExTopicOptionMapper;
import com.java.mapper.ExTopicRespMapper;
import com.java.service.ChapterService;
import com.java.service.TopicService;
import com.java.util.MyMap;
import com.java.util.MyTools;
import com.java.util.resp.BaseRespone;
import com.java.util.resp.TableRespone;

@Service
public class ChapterServiceImpl implements ChapterService {
	
	@Autowired private ExAccountMapper accountMapper;
	@Autowired private ExChapterMapper chapterMapper;
	@Autowired private ExChapterItemMapper chapterItemMapper;
	@Autowired private ExChapterRecordMapper chapterRecordMapper;
	@Autowired private ExTopicMapper topicMapper;
	@Autowired private ExTopicOptionMapper topicOptionMapper;
	@Autowired private ExTopicRespMapper topicRespMapper;
	@Autowired private TopicService topicService;

	@Override
	public BaseRespone saveChapter(ExChapter chapter) {
		ExChapter info = chapterMapper.selectByKey(chapter.getChapterId());
		BigDecimal max = chapterMapper.selectWeightCount();
		if(chapter.getChapterWeight().compareTo(new BigDecimal(0)) <= 0) {
			return BaseRespone.error("权重值需要大于0");
		}
		if(max.add(chapter.getChapterWeight()).compareTo(new BigDecimal(100)) > 0) {
			return BaseRespone.error("总权重值超过100");
		}
		int row = 0;
		if(null == info) {
			/*iList<ExTopic> tps = topicService.getAllTopic();
			f(chapter.getChapterType() == 1 ) {
				if(null == tps || tps.size() == 0) {
					return BaseRespone.result(1, "题库无数量");
				}
				if(chapter.getChapterCount() > tps.size()) {
					return BaseRespone.error("数量超过题库的" + tps.size() + "条题目");
				}
			}*/
			chapter.setChapterId(MyTools.getUUID());
			chapter.setChapterTime(new Date());
			chapter.setChapterDelete(0);
			row = chapterMapper.insertSelective(chapter);
			//if(row > 0 && chapter.getChapterType() == 1) {
				//topicService.loadTopic(chapter.getChapterId(), chapter.getChapterCount());
			//}
		}else {
			
			row = chapterMapper.updateSelective(chapter);
		}
		return BaseRespone.result(row, "保存成功");
	}

	@Override
	public BaseRespone deleteChapter(String chapterId) {
		int row = chapterMapper.deleteUpdate(chapterId, "chapter_delete");
		return BaseRespone.result(row, "删除成功", "删除失败");
	}

	@Override
	public TableRespone getChapters(Integer type, String title, int page, int pageSize) {
		MyMap mm = new MyMap().put("chapterType", type).put("chapterTitle", title).put("chapterDelete", 0);
		int offset = TableRespone.getOffset(page, pageSize);
		List<ExChapter> selectAll = chapterMapper.selectAll(mm, offset, pageSize);
		long selectAllCount = chapterMapper.selectAllCount(mm);
		return new TableRespone(selectAll, selectAllCount);
	}

	@Override
	public ExChapter getChapterInfo(String chapterId) {
		return chapterMapper.selectByKey(chapterId);
	}

	@Override
	public TableRespone getChapterVos(Integer type, String title, String accountId, int page, int pageSize) {
		int offset = TableRespone.getOffset(page, pageSize);
		List<ChapterVo> selectAll = chapterMapper.selectAllVo(type, title, accountId, offset, pageSize);
		long selectAllCount = chapterMapper.selectAllVoCount(type, title, accountId);
		return new TableRespone(selectAll, selectAllCount);
	}

	@Override
	public BaseRespone deleteChapterTopic(String chapterId, String topicId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TableRespone getChapterRecords(String title, String type, String accountId, int page, int pageSize) {
		int offset = TableRespone.getOffset(page, pageSize);
		List<ChapterRecordVo> selectAll = chapterRecordMapper.selectVoAll(title, type, accountId, offset, pageSize);
		long selectAllCount = chapterRecordMapper.selectVoAllCount(title, type, accountId);
		return new TableRespone(selectAll, selectAllCount);
	}

	@Override
	public BaseRespone getImitate(Boolean init, String accountId) {
		ExChapter exInfo = chapterMapper.selectByInfo(new ExChapter().setChapterType(1));
		String cId = MyTools.getUUID();
		if(null == exInfo) {
			exInfo = new ExChapter();
			exInfo.setChapterId(cId);
			exInfo.setChapterAccountId(accountId);
			exInfo.setChapterTitle("模拟测试" + MyTools.getDateStr(null));
			exInfo.setChapterType(1);
			exInfo.setChapterRemark("模拟测试");
			exInfo.setChapterLimit(0);
			exInfo.setChapterLimitDay(0);
			exInfo.setChapterLimitHour(0);
			exInfo.setChapterLimitMin(0);
			exInfo.setChapterCount(0);
			exInfo.setChapterTime(new Date());
			exInfo.setChapterDelete(0);
			chapterMapper.insertSelective(exInfo);
		}else {
			cId = exInfo.getChapterId();
		}
		if(init) {
			BaseRespone it = initRecord(cId, accountId);
			if(it.getStatus() == 500) {
				return BaseRespone.error(it.getMsg());
			}
		}
		return BaseRespone.success(chapterRecordMapper.selectExamLast());
	}
	
	private BaseRespone initRecord(String chapterId, String accountId) {
		int row = 0;
		boolean anew = false;
		ExChapterRecord record = chapterRecordMapper.selectExamLast();
		if(null == record) {
			record = new ExChapterRecord();
			record.setRecordId(MyTools.getUUID());
			record.setRecordChapterId(chapterId);
			record.setRecordAccountId(accountId);
			record.setRecordStatus(0);
			record.setRecordStart(new Date());
			record.setRecordTotal(new BigDecimal(0));
			record.setRecordScore(new BigDecimal(0));
			record.setRecordRight(0);
			record.setRecordWrong(0);
			anew = true;
		}else {
			chapterItemMapper.deleteExamByAccountId(accountId);
			topicRespMapper.deleteByRecordId(record.getRecordId());
		}
		BaseRespone load = topicService.loadTopic(chapterId, 100);
		if(load.getStatus() == 0) {
			return load;
		}
		if(anew) {
			row = chapterRecordMapper.insertSelective(record);
		}else {
			record.setRecordStatus(0);
			record.setRecordStart(new Date());
			record.setRecordTotal(new BigDecimal(0));
			record.setRecordScore(new BigDecimal(0));
			record.setRecordRight(0);
			record.setRecordWrong(0);
			row = chapterRecordMapper.updateSelective(record);
		}
		// 赋予实际数量
		chapterMapper.updateSelective(new ExChapter().setChapterId(chapterId).setChapterCount(load.getStatus()));
		return BaseRespone.result(row, "初始化成功", "初始化失败");
	}

	@Override
	public ExChapterRecord getChapterRecord(String chapterId, String accountId) {
		ChapterRecordVo info = chapterRecordMapper.selectVo(chapterId, accountId);
		return info;
	}

	@Override
	public ChapterRecordVo getChapterRecordVo(String chapterId, String accountId) {
		ChapterRecordVo info = new ChapterRecordVo();
		info = chapterRecordMapper.selectVo(chapterId, accountId);
		return info;
	}

	@Override
	public ChapterRecordVo initChapterRecord(String chapterId, String accountId) {
		ChapterRecordVo info = chapterRecordMapper.selectVo(chapterId, accountId);
		if(null == info) {
			ExChapterRecord record = new ExChapterRecord();
			record.setRecordId(MyTools.getUUID());
			record.setRecordStart(new Date());
			record.setRecordAccountId(accountId);
			record.setRecordStatus(0);
			record.setRecordChapterId(chapterId);
			chapterRecordMapper.insertSelective(record);
			info = chapterRecordMapper.selectVo(chapterId, accountId);
		}
		return info;
	}

	@Override
	public ChapterRecordVo getChapterRecordVoById(String recordId, String accountId) {
		ChapterRecordVo info = new ChapterRecordVo();
		info = chapterRecordMapper.selectVoById(recordId);
		return info;
	}

	@Override
	public ExChapterRecord getChapterRecord(String recordId) {
		// TODO Auto-generated method stub
		return null;
	}

	/*@Override
	public BaseRespone tempSaveRecord(String recordId, String accountId) {
		ExChapterRecord record = new ExChapterRecord();
		record.setRecordId(recordId);
		record.setRecordStatus(1);
		int row = chapterRecordMapper.updateSelective(record);
		return BaseRespone.result(row, "已临时保存", "保存异常");
	}*/

	@Override
	public BaseRespone recordFinish(String recordId, String accountId) {
		ExChapterRecord record = chapterRecordMapper.selectByKey(recordId);
		record.setRecordId(recordId);
		record.setRecordStatus(2);
		record.setRecordEnd(new Date());
		// 计算成绩
		int right = 0;
		TableRespone topicTable = topicService.getExamTopicVos(record.getRecordChapterId(), accountId, 0, 0);
		if(topicTable.getTotal() == 0) {
			return BaseRespone.error("计算的题目异常");
		}
		for (Object rowObj : topicTable.getRows()) {
			ExTopicVo vo = (ExTopicVo) rowObj;
			if(null == vo.getResp()) {
				//return BaseRespone.error("未答题完成");
			}else {
				if(vo.getResp().getRespResult() == 1) {
					right = right + 1;
				}
			}
		}
		record.setRecordRight(right);
		record.setRecordWrong((int)topicTable.getTotal() - right);
		record.setRecordTotal(new BigDecimal(topicTable.getTotal()));
		record.setRecordScore(new BigDecimal(right));
		
		int row = chapterRecordMapper.updateSelective(record);
		return BaseRespone.result(row, "已提交", "提交异常");
	}

	@Override
	public BaseRespone submitAnswer(SubmitRecord submitRecord) {
		String recordId = submitRecord.getRecordId();
		String accountId = submitRecord.getAccountId();
		SubmitRecordItem resp = submitRecord.getItem();
		ExTopicResp has = topicRespMapper.selectByInfo(new ExTopicResp()
				.setRespAccountId(accountId)
				.setRespItemId(resp.getTopicId())
				.setRespRecordId(recordId));
		int row = 0, result = 0;
		String reply = "";
		ExTopicVo topicVo = topicService.getTopicVo(resp.getTopicId());
		if(null == topicVo) {
			return BaseRespone.error("题目不存在");
		}
		if(topicVo.getTopicType() == 0) {
			reply = resp.getAnswer();
			for (ExTopicOption option : topicVo.getOptions()) {
				if(option.getOptionAnswer() == 1 && reply.equals(option.getOptionId())) {
					result = 1;
				}
			}
		} else if(topicVo.getTopicType() == 1) {
			reply = JSONObject.toJSONString(resp.getAnswers());
			List<String> rightOps = new ArrayList<String>();
			for (ExTopicOption option : topicVo.getOptions()) {
				if(option.getOptionAnswer() == 1) {
					rightOps.add(option.getOptionId());
				}
			}
			if (resp.getAnswers().size() == rightOps.size()) {
				result = 1;
				for (String op : rightOps) {
					boolean ex = false;
					for (String as : resp.getAnswers()) {
						if(op.equals(as)) {
							ex = true;
						}
					}
					// 如果答案只要其中一条匹配不到，那就直接结束循环，判定答案错误
					if(ex == false) {
						result = 0;
						break;
					}
				}
			}
		}else {
			reply = resp.getAnswer();
			if(reply.equals(topicVo.getTopicAnswer())) {
				result = 1;
			}
		}
		if(null == has) {
			has = new ExTopicResp();
			has.setRespId(MyTools.getUUID());
			has.setRespRecordId(recordId);
			has.setRespAccountId(accountId);
			has.setRespItemId(resp.getTopicId());
			has.setRespAnswer(reply);
			has.setRespResult(result);
			has.setRespTime(resp.getDateTime());
			row = topicRespMapper.insertSelective(has);
		}else {
			has.setRespAnswer(reply);
			has.setRespResult(result);
			row = topicRespMapper.updateSelective(has);
		}
		if(row > 0) {
			resp.setResult(result);
			return new BaseRespone(0, "已保存", has);
		}
		return BaseRespone.error("答题保存失败");
	}

	@Override
	public BaseRespone saveRecord(String recordId, String accountId) {
		/*ExChapterRecord record = new ExChapterRecord();
		record.setRecordId(MyTools.getUUID());
		record.setRecordStart(new Date());
		record.setRecordAccountId(accountId);
		record.setRecordStatus(0);
		record.setRecordChapterId(chapterId);
		
		int row = chapterRecordMapper.insertSelective(record);
		if(row > 0) {
			return new BaseRespone(0, "开始做题", record);
		}*/
		return BaseRespone.result(0, "正式开始做题", "开卷异常");
	}

	@Override
	public BaseRespone reStartRecord(String recordId, String accountId) {
		int row = 0;
		/*ChapterRecordVo record = chapterRecordMapper.selectVoById(recordId);
		if(record.getChapter().getChapterType() == 0) {
			record.setRecordId(recordId);
			record.setRecordStatus(0);
			record.setRecordEnd(null);
			record.setRecordRight(0);
			record.setRecordWrong(0);
			record.setRecordScore(new BigDecimal(0));
			row = chapterRecordMapper.updateSelective(record);
		}else {
			row = chapterRecordMapper.deleteByKey(recordId);
		}
		if(row > 0) {
			topicRespMapper.deleteByRecordId(recordId);
			if(record.getChapter().getChapterType() == 1) {
				chapterItemMapper.deleteExamByAccountId(accountId);
				BaseRespone imitate =  getImitate(true, accountId);
				if(imitate.getStatus() == 0) {
					return new BaseRespone(0, "已重置", imitate.getData());
				}
			}
		}*/
		ChapterRecordVo record = chapterRecordMapper.selectVoById(recordId);
		record.setRecordId(recordId);
		record.setRecordStatus(0);
		record.setRecordEnd(null);
		record.setRecordRight(0);
		record.setRecordWrong(0);
		record.setRecordScore(new BigDecimal(0));
		row = chapterRecordMapper.updateSelective(record);
		row = topicRespMapper.deleteByRecordId(recordId);
		return BaseRespone.result(row, "已重置", "重置异常");
	}

	@Override
	public BaseRespone reSelectRecord(String recordId, String accountId) {
		topicRespMapper.deleteByRecordId(recordId);
		ChapterRecordVo info = chapterRecordMapper.selectVoById(recordId);
		BaseRespone load = topicService.loadTopic(info.getRecordChapterId(), 100);
		if(load.getStatus() > 0) {
			// 赋予实际数量
			ExChapterRecord record = new ExChapterRecord();
			record.setRecordId(recordId);
			record.setRecordStatus(0);
			record.setRecordStart(new Date());
			chapterRecordMapper.updateSelective(record);
			chapterMapper.updateSelective(new ExChapter()
					.setChapterId(record.getRecordChapterId()).setChapterCount(load.getStatus()));
			return BaseRespone.success("已重新抽取");
		}
		return BaseRespone.error("重新抽取题目为空");
	}

	@Override
	public BaseRespone delAllChapter(List<String> list) {
		for (String cId : list) {
			MyMap mm = new MyMap().put("topicChapterId", cId);
			List<ExTopic> tlist = topicMapper.selectAll(mm, 0, 0);
			if(!MyTools.isEmpty(tlist)) {
				List<String> tids = new ArrayList<String>();
				for (ExTopic topic : tlist) {
					tids.add(topic.getTopicId());
				}
				topicService.delAllTopic(tids);
			}
			chapterMapper.deleteUpdate(cId, "chapter_delete");
		}
		return BaseRespone.success("已删除");
	}

	/*@Override
	public BaseRespone recordTemp(SubmitRecord submitRecord) {
		String recordId = submitRecord.getRecordId();
		String accountId = submitRecord.getAccountId();
		List<SubmitRecordItem> resps = submitRecord.getItems();
		topicRespMapper.deleteByRecordId(recordId);
		for (SubmitRecordItem resp : resps) {
			ExTopicResp eresp = new ExTopicResp();
			eresp.setRespId(MyTools.getUUID())
			.setRespItemId(resp.getTopicId())
			.setRespAccountId(accountId)
			.setRespRecordId(recordId)
			.setRespAnswer(resp.getAnswer())
			.setRespResult(resp.getResult())
			.setRespTime(resp.getDateTime());
			if(!MyTools.isEmpty(resp.getAnswers())) {
				eresp.setRespAnswer(JSONObject.toJSONString(resp.getAnswers()));
			}
			topicRespMapper.insertSelective(eresp);
		}
		return BaseRespone.result(1, "临时保存成功");
	}*/

}
